<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <!-- 引入 Tailwind CSS -->
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <!-- 引入 Font Awesome 图标库 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">
    <link href="./css/style.css" rel="stylesheet">
</head>
<body class="flex items-center justify-center min-h-screen">
<div class="card bg-white p-8 rounded-lg shadow-md w-full max-w-md mx-auto space-y-4">
    <h1 class="text-2xl font-bold text-center mb-4">注册</h1>
    <form id="register-form" class="space-y-4">
        <!-- 邮箱输入 -->
        <div>
            <label for="email" class="block text-sm font-medium text-gray-700">邮箱<span class="text-red-500">*</span></label>
            <input type="email" id="email" name="email" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <div class="error mt-1 text-red-500 text-sm hidden">请输入有效的邮箱地址</div>
        </div>
        <!-- 密码输入 -->
        <div>
            <label for="password" class="block text-sm font-medium text-gray-700">密码<span class="text-red-500">*</span></label>
            <input type="password" id="password" name="password" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <div class="error mt-1 text-red-500 text-sm hidden">密码至少包含一个字母和一个数字，且长度不少于8个字符</div>
        </div>
        <!-- 确认密码 -->
        <div>
            <label for="confirm-password" class="block text-sm font-medium text-gray-700">确认密码<span class="text-red-500">*</span></label>
            <input type="password" id="confirm-password" name="confirm-password" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <div class="error mt-1 text-red-500 text-sm hidden">两次输入的密码必须一致</div>
        </div>
        <!-- 图形验证码 -->
        <div>
            <label for="captcha" class="block text-sm font-medium text-gray-700">图形验证码<span class="text-red-500">*</span></label>
            <div class="flex items-center space-x-4">
                <img id="captcha-image" src="/api/generate-captcha" alt="Captcha" class="border border-gray-300 rounded-md flex-shrink-0 h-10 w-32">
                <button id="refresh-captcha-button" type="button" class="inline-flex items-center px-3 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 focus:outline-none focus:shadow-outline">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m9.818 9H13m-4.582-.122c-.724 1.892-1.635 3.19-2.98 4.109a60.482 60.482 0 01-10.693-3.145 59.466 59.466 0 01-4.462-10.703 60.003 60.003 0 0111.057-6.55M12 12v4.5m5.5-19.5l-1.5 1.5L12 9l-3 3 1.5 1.5m-6-3H6m6 0h6M6 18h6m6-6h-6"/>
                    </svg>
                    刷新
                </button>
            </div>
            <input type="text" id="captcha" name="captcha" required class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
            <div class="error mt-1 text-red-500 text-sm hidden">请输入正确的图形验证码答案</div>
        </div>
        <!-- 邮箱验证码 -->
        <div>
            <label for="verification-code" class="block text-sm font-medium text-gray-700">邮箱验证码<span class="text-red-500">*</span></label>
            <div class="flex items-center space-x-4">
                <input type="text" id="verification-code" name="verification-code" required class="w-2/4 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
                <button id="send-verification-code-button" type="button" class="inline-block px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 focus:outline-none focus:shadow-outline">发送验证码</button>
            </div>
            <div class="error mt-1 text-red-500 text-sm hidden">请输入收到的邮箱验证码</div>
        </div>
        <!-- 提交按钮 -->
        <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline inline-flex items-center justify-center">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 9v3m0 0v3m0-3h3m-3 0h-3m-2-5a4 4 0 11-8 0 4 4 0 018 0zM3 20a6 6 0 0112 0v-3a2 2 0 00-2-2 2 2 0 00-2 2v3a6 6 0 01-12 0v-3a2 2 0 00-2-2 2 2 0 00-2 2v3z"/>
            </svg>
            注册
        </button>
    </form>

    <div class="text-center mt-4">
        <p class="text-sm text-gray-600">已经有账号？ <a href="login.html" class="text-indigo-600 hover:text-indigo-700">立即登录</a></p>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
        // 强制前端实时验证输入
        function validateAllFields() {
            let isValid = true;
            const email = $('#email').val();
            const password = $('#password').val();
            const confirmPassword = $('#confirm-password').val();
            const captcha = $('#captcha').val();

            // 验证邮箱
            if (!validateEmail(email)) {
                showValidationError($('#email'));
                isValid = false;
            } else {
                hideValidationError($('#email'));
            }

            // 验证密码
            if (!validatePassword(password)) {
                showValidationError($('#password'));
                isValid = false;
            } else {
                hideValidationError($('#password'));
            }

            // 验证确认密码
            if (password !== confirmPassword) {
                showValidationError($('#confirm-password'));
                isValid = false;
            } else {
                hideValidationError($('#confirm-password'));
            }

            // 验证图形验证码
            if (!captcha.trim()) {
                showValidationError($('#captcha'));
                isValid = false;
            } else {
                hideValidationError($('#captcha'));
            }

            return isValid;
        }

        // 发送验证码前强制验证所有字段
        $('#send-verification-code-button').on('click', function (e) {
            e.preventDefault();
            if (validateAllFields()) {
                const email = $('#email').val();
                const password = $('#password').val();
                const confirmPassword = $('#confirm-password').val();
                const captcha = $('#captcha').val();

                $.ajax({
                    url: '/api/register',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ email, password, confirmPassword, captcha }),
                    success: function (response) {
                        alert(response.message);
                    },
                    error: function (xhr) {
                        const errorMessage = xhr.responseJSON ? xhr.responseJSON.message : "验证码发送失败，请稍后再试";
                        alert(errorMessage);
                        refreshCaptcha();
                    }
                });
            }
        });

        // 提交表单时更严格的验证
        $('#register-form').on('submit', function (e) {
            e.preventDefault();
            if (validateAllFields()) {
                const email = $('#email').val();
                const verificationCode = $('#verification-code').val();
                const password = $('#password').val();

                $.ajax({
                    url: '/api/verify-code',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ email, code: verificationCode, password }),
                    success: function (response) {
                        sessionStorage.setItem('isLoggedIn', 'true');
                        sessionStorage.setItem('userEmail', email);
                        alert('注册成功');
                        window.location.href = 'profile.html';
                    },
                    error: function (xhr) {
                        const errorMessage = xhr.responseJSON ? xhr.responseJSON.message : "注册失败，请检查验证码";
                        alert(errorMessage);
                    }
                });
            }
        });

        // 显示验证错误
        function showValidationError($input) {
            const $errorDiv = $input.next('.error');
            $errorDiv.removeClass('hidden');
        }

        // 隐藏验证错误
        function hideValidationError($input) {
            const $errorDiv = $input.next('.error');
            $errorDiv.addClass('hidden');
        }

        // 验证字段通用函数
        function validateField($input, validationFunction) {
            const value = $input.val();
            if (!validationFunction(value)) {
                showValidationError($input);
            } else {
                hideValidationError($input);
            }
        }

        // 验证邮箱格式
        function validateEmail(email) {
            const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return regex.test(email);
        }

        // 验证密码格式
        function validatePassword(password) {
            const regex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d-_]{8,}$/;
            return regex.test(password);
        }

        // 刷新图形验证码函数
        function refreshCaptcha() {
            console.log("Refreshing captcha...");
            const captchaImage = document.getElementById('captcha-image');
            captchaImage.src = '/api/generate-captcha?' + new Date().getTime(); // 添加时间戳以防止缓存
        }

        // 绑定刷新图形验证码按钮的点击事件
        document.getElementById('refresh-captcha-button').addEventListener('click', refreshCaptcha);

        // 监听输入框的 blur 事件
        $('#email').on('blur', function () {
            validateField($(this), validateEmail);
        });

        $('#password').on('blur', function () {
            validateField($(this), validatePassword);
        });

        $('#confirm-password').on('blur', function () {
            const confirmPassword = $(this).val();
            const password = $('#password').val();
            if (confirmPassword !== password) {
                showValidationError($(this));
            } else {
                hideValidationError($(this));
            }
        });

        $('#captcha').on('blur', function () {
            const captcha = $(this).val();
            if (!captcha.trim()) {
                showValidationError($(this));
            } else {
                hideValidationError($(this));
            }
        });
    });
</script>
</body>
</html>